package org.example.compositebuffer;

import io.netty.buffer.ByteBuf;
import io.netty.buffer.ByteBufAllocator;
import io.netty.buffer.CompositeByteBuf;
import io.netty.buffer.Unpooled;

import java.nio.charset.StandardCharsets;

/**
 * @author hh
 * @since 2024/11/2
 */
public class CompositeBufferTest {
    public static void main(String[] args) {
        CompositeByteBuf compositeByteBuf = ByteBufAllocator.DEFAULT.compositeBuffer();
        // 消息头
        ByteBuf headerBuf = Unpooled.copiedBuffer("你好，世界", StandardCharsets.UTF_8);
        // 消息体1
        ByteBuf bodyBuf = Unpooled.copiedBuffer("高性能Netty", StandardCharsets.UTF_8);
        compositeByteBuf.addComponents(headerBuf, bodyBuf);
        sendMsg(compositeByteBuf);
        headerBuf.retain();
        compositeByteBuf.release();

        compositeByteBuf = ByteBufAllocator.DEFAULT.compositeBuffer();
        // 消息体2
        bodyBuf = Unpooled.copiedBuffer("高性能Java", StandardCharsets.UTF_8);
        compositeByteBuf.addComponents(headerBuf, bodyBuf);
        sendMsg(compositeByteBuf);
        compositeByteBuf.release();
    }

    private static void sendMsg(CompositeByteBuf compositeByteBuf) {
        // 处理整个消息
        for (ByteBuf byteBuf : compositeByteBuf) {
            int length = byteBuf.readableBytes();
            byte[] bytes = new byte[length];
            // 将compositeByteBuf中的数据统一复制到数组中
            byteBuf.getBytes(byteBuf.readerIndex(), bytes);
            // 处理一下数组中的数据
            System.out.println(new String(bytes, StandardCharsets.UTF_8));
        }
        System.out.println();
    }
}
